﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PMS.Core.Infrastructure;
using PMS.Core.Utils;
using PMS.Web.Framework.Validators.IllegalWords;
using System.Collections.Generic;
using System.IO;

namespace PMS.Web.Framework.StartupCfgs.StartupTasks
{
    /// <summary>
    /// Load IllegalWords From gzip json file to filte Sensitive-Words
    /// Using ToolGood.Words
    /// </summary>
    public class LoadIllegalWordJsonStartUpTask : IStartupTask
    {
        private const string GZJSONFILEPATH = "~/App_Data/IllegalKeywords.json.gz";
        public int Order => StartupTaskOrderConfig.LoadIllegalWordsJsonOrder;

        public void Execute()
        {
            var fileProvider = CommonHelper.DefaultFileProvider;
            var illegalFilePath = fileProvider.MapPath(GZJSONFILEPATH);
            if (fileProvider.FileExists(illegalFilePath))
            {
                using (var sr = new StreamReader(CommonHelper.DecompressFromFileAsync(illegalFilePath).Result))
                using (var jsonTextReader = new JsonTextReader(sr))
                {
                    var wordsJson = JObject.Load(jsonTextReader);
                    var keys = JsonConvert.DeserializeObject<List<string>>(wordsJson["IllegalKeywords"].ToString());
                    IllegalWordsProvider.Instance.SetKeys(keys);
                }
            }
        }
    }
}
